package edu.ccut.saturn.basecomponent.database.facade;

import java.sql.Connection;
import java.util.List;

import edu.ccut.saturn.basecomponent.database.ISelectSQLBuilder;
import edu.ccut.saturn.basecomponent.database.ISaturnSQL;
import edu.ccut.saturn.basecomponent.database.ISaturnSQLBuilder;
import edu.ccut.saturn.basecomponent.database.SaturnSQLBuilderFactory;
import edu.ccut.saturn.basecomponent.database.SaturnSQLHandler;
import edu.ccut.saturn.basecomponent.database.util.SaturnDataUtil;
import edu.ccut.saturn.component.IDataItem;
import edu.ccut.saturn.component.SaturnComponentException;
import edu.ccut.saturn.component.SaturnData;

public class QueryByPrimaryKey {
	public SaturnData execute(String fullKey ,String primaryKeyValue,Connection conn) throws Exception {
		String dbType = SaturnDataUtil.getStandardDBType(fullKey);
		ISaturnSQLBuilder builder = SaturnSQLBuilderFactory.getSaturnSQLBuilder(dbType);
		if(builder!=null){
			if (primaryKeyValue == null) {
				throw new SaturnComponentException(
						"PrimaryKey can not be null !");
			}
			IDataItem item = SaturnDataUtil.getPKDataItem(fullKey);
			if (item == null) {
				throw new SaturnComponentException(
						"Can not find primaryKey in SaturnData name is" + fullKey);
			}
			String condition = " WHERE " + item.getColumn() + " ='" + primaryKeyValue + "' ";
			ISelectSQLBuilder selectSQLBuilder = builder.getSelectSQLBuilder(getBuilderType(fullKey));
			ISaturnSQL saturnSQL = selectSQLBuilder.build(fullKey, condition);
			List<SaturnData> list = SaturnSQLHandler.executeQuery(saturnSQL, conn);
			if(list!=null){
				return list.get(0);
			}
		}
		return null;
	}
	private String getBuilderType(String fullKey) {
		// 如果有大数据
		if (SaturnDataUtil.hasLOB(fullKey)) {
			return ISaturnSQL.SELECT_LOB_OPERATION;
		} else {
			return ISaturnSQL.SELECT_OPERATION;
		}
	}

//	private boolean hasLOB(String fullKey) {
//		IDataInfo dataInfo = SaturnDataManager.getInstance().getSaturnDataInfo(
//				fullKey);
//		for (String key : dataInfo.keySet()) {
//			IDataItem dataItem = dataInfo.getDataItem(key);
//			if (OracleAttribute.isLOB(dataItem.getType())) {
//				return true;
//			}
//		}
//		return false;
//	}
}
